<template>
  <view class="container">
    <!-- 顶部区域 (包含统计卡片) -->
    <view class="header-container">
      <view class="header">
        <u-avatar :size="80" shape="circle" :src="userInfo.avatar || '/static/default-avatar.png'"
                  @click="goToProfile"/>
        <view class="user-info" @click="goToProfile">
          <view class="nickname-container">
            <text class="nickname">{{ userInfo.nickname || '未设置昵称' }}</text>
            <u-icon :name="userInfo.sex === 1 ? 'man' : 'woman'" size="20"
                    :color="userInfo.sex === 1 ? '#36BFFA' : '#FF80BF'"/>
          </view>
          <text class="userId">ID: {{ userInfo.userId || '未设置ID' }}</text>
        </view>
        <u-icon name="arrow-right" size="20" color="#333" @click="goToProfile"/>
      </view>

      <!-- 统计卡片 -->
      <view class="stats-card">
        <view class="stats-item" @click="goToLikes">
          <text class="stats-value">{{ userInfo.likeCount || 0 }}</text>
          <text class="stats-label">获赞</text>
        </view>
        <view class="stats-item" @click="goToMutualFollow">
          <text class="stats-value">{{ userInfo.mutualFollowCount || 0 }}</text>
          <text class="stats-label">互关</text>
        </view>
        <view class="stats-item" @click="goToFollow">
          <text class="stats-value">{{ userInfo.followCount || 0 }}</text>
          <text class="stats-label">关注</text>
        </view>
        <view class="stats-item" @click="goToFans">
          <text class="stats-value">{{ userInfo.fanCount || 0 }}</text>
          <text class="stats-label">粉丝</text>
        </view>
      </view>
    </view>

    <!-- 中间功能区 - 签到、优惠券、钱包 -->
    <view class="finction-box">
      <up-box height="180px" gap="10px" :bgColors="['transparent', 'transparent', 'transparent']"
              customStyle="border-radius: 12rpx; overflow: hidden; box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);">
        <!-- 左侧签到模块 -->
        <template #left>
          <view class="sign-in-container" @click="goToSignCalendar">
            <image class="sign-in-bg" src="/static/picture/sign-bg.png" mode="cover"></image>
            <view class="sign-in-content">
              <text class="sign-in-text">每日签到领福利</text>
              <text class="sign-in-days">本月已签到{{ userInfo.signCount || 0 }}天</text>
              <up-button
                  :text="hasSigned ? '已签到' : '去签到'"
                  type="info"
                  plain
                  size="mini"
                  shape="circle"
                  customStyle="width: 130rpx"
              >
              </up-button>
            </view>
          </view>
        </template>

        <!-- 右上优惠券 -->
        <template #rightTop>
          <view class="coupon-container" @click="goToCoupon">
            <image class="bg-image" src="/static/picture/coupon-bg.png" mode="cover"/>
            <view class="content-container">
              <u-icon name="coupon" size="28" color="#974B00"/>
              <text class="coupon-text">优惠券</text>
              <text class="coupon-count">3张可用</text>
            </view>
          </view>
        </template>

        <!-- 右下钱包 -->
        <template #rightBottom>
          <view class="wallet-container" @click="goToWallet">
            <image class="bg-image" src="/static/picture/wallet-bg.png" mode="cover"/>
            <view class="content-container">
              <u-icon name="rmb-circle" size="26" color="#FFD8B5"/>
              <view class="wallet-header">
                <text class="wallet-text">我的钱包</text>
                <up-icon :name="showBalance ? 'eye' : 'eye-off'" size="36rpx" color="#754312"
                         @tap.stop="toggleBalance"></up-icon>
              </view>
              <view class="wallet-balance" v-show="showBalance">
                <text>¥</text>
                <up-count-to
                    :start-val="0"
                    :end-val="endVal"
                    :decimals="2"
                    :duration="duration"
                    color="#FFD8B5"
                    font-size="30rpx"
                    separator=","></up-count-to>
              </view>
              <!-- 隐藏时显示星号 -->
              <text v-show="!showBalance" class="hidden-balance">******</text>
            </view>
          </view>
        </template>
      </up-box>
    </view>

    <!-- 功能入口 -->
    <view class="function-container">
      <view class="function-grid">
        <u-grid :col="3" :border="false" :show-header="false">
          <u-grid-item v-for="(item, index) in functionList" :key="index" @click="item.action">
            <u-icon :name="item.icon" size="32" :customStyle="{paddingTop: '20rpx'}"/>
            <text class="grid-text">{{ item.text }}</text>
          </u-grid-item>
        </u-grid>
      </view>
    </view>

    <!-- 底部功能区 -->
    <view class="action-container">
      <view class="action-item" @click="studentCertification">
        <u-icon name="checkbox-mark" size="24" color="#36BFFA"/>
        <text class="action-text">学生认证</text>
        <u-icon name="arrow-right" size="18" color="#999"/>
      </view>
      <view class="action-item" @click="feedback">
        <u-icon name="question-circle" size="24" color="#36BFFA"/>
        <text class="action-text">意见反馈</text>
        <u-icon name="arrow-right" size="18" color="#999"/>
      </view>
      <view class="action-item" @click="contactCustomerService">
        <u-icon name="server-man" size="24" color="#36BFFA"/>
        <text class="action-text">AI智能客服</text>
        <u-icon name="arrow-right" size="18" color="#999"/>
      </view>
      <view class="action-item" @click="goToAboutUs">
        <u-icon name="account" size="24" color="#36BFFA"/>
        <text class="action-text">关于我们</text>
        <u-icon name="arrow-right" size="18" color="#999"/>
      </view>
    </view>

  </view>
  <FloatingBall v-if="false"/>
  <AiServerDialog/>
  <my-custom-tab-bar/>
</template>

<script setup>
import {ref, onMounted, watch} from 'vue';
import {onShow} from '@dcloudio/uni-app';
import {getUserInfo} from '../../apis/userAPI';
import {getSignedStatusByMonth, getTotalSignCount} from '@/apis/userSignAPI';
import MyCustomTabBar from "@/components/custom-tab-bar/my-custom-tab-bar.vue";
import {useAiServerChatStore} from '@/store/aiServerChatStore';

// 从本地存储获取用户ID，并添加安全检查
const userId = ref(null);
const fetchingUserId = ref(true);

// 用户信息
const userInfo = ref({
  userId: 0,
  username: '',        // 用户名
  nickname: '',        // 昵称
  password: '',        // 密码（实际项目中通常不返回明文密码）
  avatar: '',          // 头像URL
  email: '',           // 邮箱
  phone: '',           // 手机号
  createTime: '',      // 创建时间
  updateTime: '',      // 更新时间
  isDeleted: 0,        // 是否删除（0:未删除，1:已删除）
  sex: 0,              // 性别（0:未知，1:男，2:女）
  isAuth: 0,           // 是否认证
  grade: 0,            // 等级
  balance: 0,          // 余额
  coin: 0,             // 金币
  likeCount: 0,        // 获赞数
  mutualFollowCount: 0,// 互关数量
  followCount: 0,      // 关注数量
  fanCount: 0,         // 粉丝数量
  postCount: 0,        // 发布内容数量
  signCount: 0    // 连续签到天数
})

// 创建响应式数据 数字滚动endVal
const endVal = ref(0);
const duration = ref(1600);

// 控制金额显示/隐藏
const showBalance = ref(true);

// 签到状态
const hasSigned = ref(false);
const showSignModal = ref(false);
const showSignSuccess = ref(false);

// 获取 AI 聊天状态管理实例
const aiStore = useAiServerChatStore();

// 跳转到签到日历页面
const goToSignCalendar = () => {
  uni.navigateTo({
    url: '/pages/mine/calendar',
    fail: (err) => {
      console.error('页面跳转失败:', err)
      uni.showToast({
        title: '跳转失败，请稍后再试',
        icon: 'none'
      })
    }
  })
}

// 功能列表数据
const functionList = ref([
  {icon: 'file-text', text: '我的帖子', action: () => goToPosts()},
  {icon: 'order', text: '我的订单', action: () => goToOrders()},
  {icon: 'bag', text: '我的闲置', action: () => goToIdleItem()}
])

// 生命周期钩子
onMounted(() => {
  // 获取用户ID
  const userInfoStorage = uni.getStorageSync('userInfo');
  if (userInfoStorage && userInfoStorage.userId) {
    userId.value = userInfoStorage.userId;
    fetchingUserId.value = false;
    fetchUserInfo();
  } else {
    fetchingUserId.value = false;
    console.error('未找到用户ID，请检查登录状态');
    // 可以在这里跳转到登录页面
    uni.showToast({
      title: '请先登录',
      icon: 'none',
      success: () => {
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/login/login'
          });
        }, 1500);
      }
    });
  }
});

// 监听userId变化，获取用户信息
watch(userId, (newUserId) => {
  if (newUserId) {
    fetchUserInfo();
  }
});

// 页面每次显示时刷新数据
onShow(() => {
  if (userId.value) {
    fetchUserInfo();
  }
});

// 获取用户失败重试次数
const retryCount = ref(3);

// 获取用户信息方法
const fetchUserInfo = async () => {
  try {
    // 显示加载提示
    uni.showLoading({
      title: '加载中...',
      mask: true
    })

    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;

    // 并发请求用户信息和签到状态
    const [userResponse, signResponse, signCountResponse] = await Promise.all([
      getUserInfo(userId.value),
      getSignedStatusByMonth(userId.value, year, month),
      getTotalSignCount(userId.value, year, month)
    ]);

    // 处理用户信息
    if (userResponse.statusCode === 200 && userResponse.data.code === 200) {
      userInfo.value = userResponse.data.data;
      endVal.value = userInfo.value.balance || 0;
      console.log('用户信息获取成功:', userInfo.value);
    } else {
      console.error('获取用户信息失败:', userResponse);
      throw new Error('获取用户信息失败');
    }

    // 处理签到状态
    if (signResponse.data.code === 200) {
      const signStatusArray = signResponse.data.data || [];
      const today = new Date().getDate();
      hasSigned.value = signStatusArray[today - 1] === true;
    } else {
      console.error('获取签到状态失败:', signResponse);
      throw new Error('获取签到状态失败');
    }

    // 处理本月签到总次数
    if (signCountResponse.data.code === 200) {
      userInfo.value.signCount = signCountResponse.data.data;
    } else {
      console.error('获取本月签到总次数失败:', signCountResponse);
      throw new Error('获取本月签到总次数失败');
    }
  } catch (error) {
    uni.showToast({
      title: '网络请求失败，请重试',
      icon: 'none'
    });
    if (retryCount.value > 0) {
      fetchUserInfo();
    }
    retryCount.value--;
  } finally {
    // 隐藏加载提示
    uni.hideLoading();
  }
}

// 导航方法
const goToCoupon = () => {
  uni.navigateTo({
    url: '/pages/mine/coupon' // 根据实际路径修改
  });
};

const goToWallet = () => {
  // uni.showToast({
  //   title: '跳转到钱包页面',
  //   icon: 'none'
  // })
}

// 切换金额显示状态
const toggleBalance = () => {
  showBalance.value = !showBalance.value
}

// 导航方法
const goToMutualFollow = () => {
  uni.navigateTo({
    url: `/pages/mine/relationshipList/relationshipList?activeTab=0`
  });
};

const goToFollow = () => {
  uni.navigateTo({
    url: `/pages/mine/relationshipList/relationshipList?activeTab=1`
  });
};

const goToFans = () => {
  uni.navigateTo({
    url: `/pages/mine/relationshipList/relationshipList?activeTab=2`
  });
};

// 其他导航方法 - 暂时使用空函数
const goToProfile = () => {
  uni.navigateTo({
    url: `/pages/profile/profile`
  });
}
const goToLikes = () => {
}
const goToPosts = () => {
  uni.navigateTo({
    url: `/pages/profile/profile?currentTab=0`
  })
}
const goToOrders = () => {
  uni.navigateTo({
    url: `/pages/myOrder/myOrder`
  })
}
const goToIdleItem = () => {
  uni.navigateTo({
    url: `/pages/profile/profile?currentTab=1`
  })
}
const goToAccountManage = () => {
}
const goToPrivacySetting = () => {
}
const goToGeneralSetting = () => {
}
const goToAboutUs = () => {
}
const goToHelpCenter = () => {
}

// 操作方法
const studentCertification = () => {
  uni.showModal({
    title: '学生认证',
    content: '此功能暂未开放，敬请期待',
    showCancel: false
  })
}

const feedback = () => {
  uni.showModal({
    title: '意见反馈',
    content: '此功能暂未开放，敬请期待',
    showCancel: false
  })
}

const contactCustomerService = () => {
  aiStore.toggleDialog(true);
}
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background-color: #f7f7f7;
  min-height: 100vh;
}

.header-container {
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  overflow: hidden; // 确保圆角生效

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx;

    .user-info {
      flex: 1;
      margin-left: 20rpx;

      .nickname-container {
        display: flex;
        align-items: center;
        margin-bottom: 8rpx;

        .nickname {
          font-size: 36rpx;
          font-weight: bold;
          margin-right: 10rpx;
        }
      }

      .userId {
        font-size: 24rpx;
        color: #666;
      }
    }
  }

  // 统计卡片样式
  .stats-card {
    display: flex;
    padding: 15rpx 0;
    border-top: 1rpx solid #eee;

    .stats-item {
      flex: 1;
      text-align: center;

      .stats-value {
        font-size: 30rpx;
        font-weight: bold;
        display: block;
      }

      .stats-label {
        font-size: 22rpx;
        color: #666;
        display: block;
        margin-top: 4rpx;
      }
    }
  }
}

// 中间功能区样式
.finction-box {
  margin-bottom: 20rpx;
}

// 签到区域样式
.sign-in-container {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 10rpx;
  overflow: hidden;

  .sign-in-bg {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 1;
  }

  .sign-in-content {
    position: relative;
    z-index: 2;
    width: 90%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: rgba(0, 0, 0, 0);
    color: #006DBA;
    padding: 15rpx;

    .sign-in-text {
      font-size: 28rpx;
      font-weight: bold;
      margin-bottom: 10rpx;
    }

    .sign-in-days {
      font-size: 22rpx;
      margin-bottom: 15rpx;
    }

  }
}

// 优惠券区域样式
.coupon-container {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 10rpx;
  overflow: hidden;

  .bg-image {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 1;
  }

  .content-container {
    position: relative;
    z-index: 2;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 15rpx;
    background-color: transparent; // 移除半透明背景
  }

  .coupon-text {
    font-size: 26rpx;
    margin-top: 8rpx;
    color: #974B00;
    font-weight: 500;
  }

  .coupon-count {
    font-size: 22rpx;
    color: #974B00;
    margin-top: 5rpx;
    font-weight: 500;
  }
}

// 钱包区域样式
.wallet-container {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 10rpx;
  overflow: hidden;

  .bg-image {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 1;
  }

  .content-container {
    position: relative;
    z-index: 2;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 15rpx;
    background-color: transparent; // 移除半透明背景
  }

  .wallet-header {
    display: flex;
    align-items: center;
    gap: 8rpx;
    margin-bottom: 8rpx;
  }

  .wallet-text {
    font-size: 26rpx;
    margin-top: 8rpx;
    color: #FFD8B5;
    font-weight: 500;
  }

  .wallet-balance {
    font-size: 30rpx;
    color: #FFD8B5;
    margin-top: 5rpx;
    font-weight: 500;
  }

  // 隐藏金额时显示的星号样式
  .hidden-balance {
    font-size: 30rpx;
    color: #FFD8B5;
    font-weight: bold;
  }
}

.function-container {
  background-color: #fff;
  border-radius: 12rpx;
  margin-top: 0;
  margin-bottom: 20rpx;
  padding: 20rpx 0;

  .function-grid {
    padding: 0 10rpx;
  }
}

// 底部功能区样式
.action-container {
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;

  .action-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 25rpx 20rpx;
    border-bottom: 1rpx solid #eee;

    .action-text {
      font-size: 28rpx;
      margin-left: 15rpx;
      flex: 1;
    }
  }
}

.grid-text {
  font-size: 24rpx;
  color: #666;
  padding: 10rpx 0 20rpx 0;
}

// 签到弹窗样式
.sign-modal-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 0;

  .sign-success-icon {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20rpx;

    .sign-success-text {
      font-size: 28rpx;
      color: #333;
      margin-top: 10rpx;
      font-weight: bold;
    }
  }

  .sign-info {
    text-align: center;
    font-size: 24rpx;
    color: #666;
    line-height: 1.5;
  }

  .already-signed {
    font-size: 26rpx;
    color: #333;
    margin-bottom: 15rpx;
  }

  .sign-tip {
    font-size: 22rpx;
    color: #999;
  }

  .not-signed {
    font-size: 24rpx;
    color: #666;
    margin-bottom: 20rpx;
  }

  .modal-sign-btn {
    width: 80%;
    height: 80rpx;
    line-height: 80rpx;
    font-size: 26rpx;
  }
}
</style>